package com.ray.finance.strategy.advance.edit;

import com.alibaba.fastjson.JSON;
import com.ray.business.check.PurchaseCheck;
import com.ray.business.service.ProdPurchaseService;
import com.ray.business.table.entity.ProdPurchase;
import com.ray.finance.builder.AdvanceBuilder;
import com.ray.finance.check.AdvanceCheck;
import com.ray.finance.service.FinaAdvanceService;
import com.ray.finance.table.entity.FinaAdvance;
import com.ray.finance.table.params.advance.AdvanceEditParams;
import com.ray.magicBlock.Strategy;
import com.ray.magicBlock.anno.Block;
import com.ray.system.enums.FileTypeEnum;
import com.ray.system.service.SysFileService;
import com.ray.util.FileRecordUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author bo shen
 * @Description: 预付款单
 * @Class: SaleInService
 * @Package com.ray.wms.strategy.in
 * @date 2020/6/8 15:05
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Block(group = "editAdvance", strategy = "PURCHASE", desc = "采购订单预付款单")
public class PurchaseEditService implements Strategy<AdvanceEditParams, LoginUser, String> {

    @Autowired
    private ProdPurchaseService prodPurchaseService;
    @Autowired
    private FinaAdvanceService finaAdvanceService;
    @Autowired
    private SysFileService sysFileService;

    @Override
    public String execute(AdvanceEditParams editParams, LoginUser loginUser) {
        //查询订单是否存在
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(editParams.getOrderNo(),loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购订单不存在").checkCanAdvance("订单已经完成");
        //查询订单是否已经存在预付款单
        FinaAdvance finaAdvance = finaAdvanceService.queryAdvanceByOrderNo(editParams.getOrderNo(),loginUser);
        new AdvanceCheck(finaAdvance).checkNull("预付款记录不存在").checkAmount(editParams.getAmount(),"修改后的今天不能小于已使用金额");
        AdvanceBuilder advanceBuilder = new AdvanceBuilder();
        advanceBuilder.append(editParams).append(prodPurchase).appendEdit(loginUser);
        if(!finaAdvanceService.edit(advanceBuilder.bulid(),loginUser)){
            log.info("编辑预付款单异常:{}", JSON.toJSONString(advanceBuilder.bulid()));
            throw BusinessExceptionFactory.newException("编辑预付款单异常");
        }
        //删除文件
        sysFileService.deleteFile(editParams.getAdvanceCode(), FileTypeEnum.ADVANCE.getValue(),loginUser);
        //保存文件
        sysFileService.saveFile(editParams.getAdvanceCode(), FileTypeEnum.ADVANCE, FileRecordUtil.toFileDTO(editParams.getFiles()),loginUser);
        return advanceBuilder.getCode();
    }
}
